package com.atguigu.flink.chapter05.sink;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Flink04_Sink_Custom {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        DataStream<WaterSensor> s1 =
                //            env.socketTextStream("hadoop162", 9999)
                env.fromElements(
                        new WaterSensor("sensor_1", 1L, 10),
                        new WaterSensor("sensor_1", 2L, 20),
                        new WaterSensor("sensor_1", 5L, 20),
                        new WaterSensor("sensor_2", 3L, 30),
                        new WaterSensor("sensor_1", 4L, 40),
                        new WaterSensor("传感器", 4L, 40)
                );

        s1.addSink(new MysqlSink());

        env.execute();
    }

    private static class MysqlSink extends RichSinkFunction<WaterSensor> {

        private Connection conn;
        private PreparedStatement ps;

        @Override
        public void open(Configuration parameters) throws Exception {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://hadoop162:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false", "root", "aaaaaa");
            // ps = conn.prepareStatement("insert into sensor values(?, ?, ?)");
            ps = conn.prepareStatement("insert into sensor values(?, ?, ?) on duplicate key update vc=?");
            // ps = conn.prepareStatement("replace into sensor values(?, ?, ?)");
        }

        @Override
        public void invoke(WaterSensor value, Context context) throws Exception {
            ps.setString(1, value.getId());
            ps.setLong(2, value.getTs());
            ps.setInt(3, value.getVc());
            ps.setInt(4, value.getVc());

            ps.execute();
        }

        @Override
        public void close() throws Exception {
            if (ps != null) {
                ps.close();
            }

            if (conn != null) {
                ps.close();
            }
        }
    }
}
